package com.ruoyi.merchant.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.dto.MerchantAuditRequest;
import com.ruoyi.merchant.domain.vo.MerchantAuditDetailVO;
import com.ruoyi.merchant.domain.vo.MerchantAuditListVO;
import com.ruoyi.merchant.domain.vo.MerchantAuditResponse;
import com.ruoyi.merchant.service.IMerchantAuditService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商家审核Controller
 */
@RestController
@RequestMapping("/admin/merchant/audit")
public class MerchantAuditController extends BaseController {

    @Autowired
    private IMerchantAuditService auditService;

    /**
     * 查询待审核商家列表
     */
    @PreAuthorize("@ss.hasPermi('merchant:audit:list')")
    @GetMapping("/list")
    public TableDataInfo list(Merchant merchant) {
        startPage();
        List<Merchant> list = auditService.selectAuditList(merchant);
        
        // 转换为VO
        List<MerchantAuditListVO> voList = list.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
        
        return getDataTable(voList);
    }

    /**
     * 获取商家审核详情
     */
    @PreAuthorize("@ss.hasPermi('merchant:audit:query')")
    @GetMapping("/detail/{merchantId}")
    public AjaxResult getDetail(@PathVariable Long merchantId) {
        MerchantAuditDetailVO detail = auditService.getAuditDetail(merchantId);
        return AjaxResult.success(detail);
    }

    /**
     * 审核商家入驻申请
     */
    @PreAuthorize("@ss.hasPermi('merchant:audit:process')")
    @Log(title = "商家审核", businessType = BusinessType.UPDATE)
    @PostMapping("/process")
    public AjaxResult process(@Validated @RequestBody MerchantAuditRequest request) {
        // 参数校验
        request.validate();
        
        // 获取当前登录用户信息
        Long auditorId = SecurityUtils.getUserId();
        String auditorName = SecurityUtils.getUsername();
        
        // 执行审核
        MerchantAuditResponse response = auditService.processAudit(
            request, auditorId, auditorName);
        
        return AjaxResult.success("审核成功", response);
    }

    /**
     * 获取审核统计
     */
    @PreAuthorize("@ss.hasPermi('merchant:audit:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics() {
        Map<String, Integer> statistics = auditService.getAuditStatistics();
        return AjaxResult.success(statistics);
    }

    /**
     * 转换为列表VO
     */
    private MerchantAuditListVO convertToListVO(Merchant merchant) {
        MerchantAuditListVO vo = new MerchantAuditListVO();
        BeanUtils.copyProperties(merchant, vo);
        
        String auditStatus = com.ruoyi.common.utils.StringUtils.defaultIfBlank(
            merchant.getExternField1(), "PENDING_INFO");
        vo.setAuditStatus(auditStatus);
        vo.setAuditStatusText(getAuditStatusText(auditStatus));
        
        // 解析提交时间
        if (merchant.getExternField2() != null) {
            try {
                vo.setSubmitTime(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse(merchant.getExternField2()));
            } catch (Exception e) {
                // 忽略
            }
        }
        
        return vo;
    }

    /**
     * 获取审核状态文本
     */
    private String getAuditStatusText(String auditStatus) {
        switch (auditStatus) {
            case "PENDING_INFO": return "待完善信息";
            case "UNDER_REVIEW": return "审核中";
            case "APPROVED": return "已通过";
            case "REJECTED": return "已拒绝";
            default: return "未知状态";
        }
    }
}
